<template>
    <RenderOperation/>
</template>
<script lang="jsx" setup name="v3Operation">
/* 只关注页面操作区域的按钮逻辑，和query、table、dialog里面的按钮的请求 */
import { ref, useSlots, watchEffect } from 'vue'
import { isArray } from '@/utils/tools'
const emit = defineEmits(['up', 'fetch', 'event']);
import { useFetch } from '@/hooks/fetch'
import dropdown from './dropdown.vue'
import v3Button from './v3Button.vue'
const v3OperationRef = ref()
const slots = useSlots();
const props = defineProps({
    schema: {
        type: Object,
        default: () => {}
    },
    operationSlotIdx: {
        type: [Number, Array],
        default: 0
    }
})

const schema = {
    type: "primary",
    disabled: false, // 是否禁用
    ...props.schema
}
// console.log('v3-operation--schema--', schema)
const { operationSlotIdx: slotIdx } = props

const privateFn = {
    fetch: async (config, data = {}) => {
        const { request, wgtName } = config
        request.params = data
        console.log('privateFn--operation--fetch-', config, data)
        /* 导出 */
        if (request?.responseType === 'blob') {
          await useFetch(request)
          return
        } 
        const { body, error } = await useFetch(request)
        if (error) {
            return error
        }
        const { successCb, hookFn } = request
        if (successCb) {
            emit('up', {index: schema.index, ...successCb})
        }
        if (hookFn) {
            emit('event', {"widgetName": wgtName || 'operation', ...request, ...body})
        }
        return body
    }
}
const handler = (config = {}, data = {}) => {
    console.log('v3-operation--handler--', config, data)
    const { actOn, rangeFn, isCustom, rangeFnExcuteJs, hookFn } = config
    if (isCustom || hookFn) {
        console.log('v3-operation--isCustom--', config, data)
        emit('event', {"widgetName": 'operation', ...config, ...data})
    } else if (!actOn && privateFn[rangeFn]) {
        privateFn[rangeFn](config, data)
    } else {
        let result
        emit('up', {index: schema.index, ...config}, data, result => {
            // if (fn instanceof Function) {
                // result = fn(config, data) || {}
                if (rangeFnExcuteJs) {
                    const evaluate = new Function("obj", `return ${rangeFnExcuteJs}`);
                    result = evaluate(result);
                }
                Object.assign(result, data, config.label && {'label': config.label})
                /* 一级request, rangeFn == fetch 、update 已自带请求方法 */
                if (config.request && rangeFn != 'fetch' && rangeFn != 'update') {
                    privateFn.fetch(config, result)/* .then(res => {
                        if (res.isError) return
                        // console.log('v3-operation--fetch--', res, config)
                        if (config.request.successCb) {
                            emit('up', {index: schema.index, ...config.request.successCb}, fn => {
                                fn && fn(config.request.successCb)
                            })
                        }
                    }) */
                }
                if (config.next) {
                    handler(config.next, result)
                }
            // }
        })
    }
}
watchEffect(() => {
    if (props.operationSlotIdx) {
        const slotIdx = props.operationSlotIdx
        if (isArray(slotIdx)) {
            slotIdx.forEach((item, i) => {
            schema.items.splice(item, 0, {type: 'slot', idx: item, isShow: true})
          })
        } else {
          schema.items.splice(slotIdx, 0, {type: 'slot', idx: slotIdx, isShow: true})
        }
    }
})
defineExpose({ 
    "fetch": privateFn.fetch
})
/* slots.operationItem ? slots.operationItem(obj)[0].children[idx] */
const RenderOperation = () =>
    <div class={'buttonList'} ref={v3OperationRef}>
        {
            schema.items.map((item, index) => {
                const { label, type, disabled, isShow, className, style, dropdownMenus, triggerType, size, icon, button } = item
                const btnConfig ={ label, type, className, style, size, icon, disabled, ...button }
                if (!isShow) return null;
                const i = isArray(slotIdx) && slotIdx.findIndex(n => (n === item.idx && item.type === 'slot'));
                return dropdownMenus?.length
                ?   <dropdown config={item} triggerType={triggerType} onClickItem={subItem => handler(subItem)}/>
                :   type === 'slot'
                ?   (isArray(slotIdx) && item.idx === index && slots.operationItem) ? slots.operationItem({item, index})[0].children[i]
                :   slots.operationItem({item, index})
                :   <v3Button config={btnConfig} onClick={() => handler(item)}/>
            })
        }
    </div>
</script>
<style scoped>
.buttonList{
    margin-bottom: 20px;
}
</style>
<style>
.buttonList .el-button + .el-dropdown, .buttonList .el-dropdown  + .el-button{
    margin-left: 12px;
}
</style>
